package com.thinkcoder.util;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class Md5Util {

    private static final String ALGORITHM="MD5";

    /**
     * 获得摘要
     *
     * @param input 输入字符
     * @return
     * @throws Exception
     */
    public static String encrypt(String input) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM);
        // 消息数字摘要
        byte[] digest = messageDigest.digest(input.getBytes());
        System.out.println("密文的字节长度:" + digest.length);

        return toHex(digest);
    }

    /**
     * 摘要结果转换为16进制
     *
     * @param digest
     * @return
     */
    private static String toHex(byte[] digest){

        //创建对象用来拼接
        StringBuilder sb = new StringBuilder();

        for (byte b : digest) {
            // 转成 16进制
            String s = Integer.toHexString(b & 0xff);
            if (s.length() == 1){
                // 如果生成的字符只有一个，前面补0
                s = "0"+s;
            }
            sb.append(s);
        }
        System.out.println("16进制数据的长度：" + sb.toString().getBytes().length);
        return sb.toString();
    }


    public static void main(String[] args) throws Exception{
        Map<String, String> map = new HashMap<>();
        map.put("url", "abc");
        map.put("name", "name");
        String mapStr = map.toString();
        String content1 = Md5Util.encrypt(mapStr);

        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "name");
        map2.put("url", "abc");

        String mapStr2 = map2.toString();
        String content2 = Md5Util.encrypt(mapStr2);

        //证明map的消息摘要不分参数顺序
        System.out.println(content1.equals(content2));
    }
}
